package top.bug.blog.interceptor;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.bug.blog.annotation.Auth;
import top.bug.blog.common.UserContext;
import top.bug.blog.enums.ErrorCode;
import top.bug.blog.exception.BussinessException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description 权限校验拦截器
 */
@Component
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 检查是否是 HandlerMethod，避免对静态资源的请求抛出异常
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获得被拦截的方法对象
        Method method = handlerMethod.getMethod();
        // 获得方法上的注解
        Auth methodAuth = method.getAnnotation(Auth.class);
        // 检查类上的注解
        Auth classAuth = handlerMethod.getBeanType().getAnnotation(Auth.class);
        if (classAuth != null || methodAuth != null) {
            String userId = UserContext.getUserId();
            // 需要校验并且没有登录
            boolean check = null == methodAuth ? classAuth.isCheck() : methodAuth.isCheck();
            if (check && StrUtil.isBlank(userId)) {
                log.error("权限校验失败，访问接口：{}", request.getRequestURI());
                // 未登录，抛出异常
                throw new BussinessException(ErrorCode.PERMISSION_UNAUTHORIZED);
            }
        }
        return true;
    }
}